package dao;

import model.Shopping_cart;
import util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class Shopping_cartDao {


    public List<Shopping_cart> getCartItemsByUserId(int userId) throws SQLException {
        List<Shopping_cart> cartItems = new ArrayList<>();
        String query = "SELECT * FROM shopping_cart WHERE user_id = ?";

        JDBCUtil jdbcUtil = new JDBCUtil();
        try {

            ResultSet resultSet = jdbcUtil.prepareQuery(query,  userId);

            while (resultSet.next()) {
                Shopping_cart cartItem = new Shopping_cart();
                cartItem.setUser_id(resultSet.getInt("user_id"));
                cartItem.setGoods_id(resultSet.getInt("goods_id"));
                cartItem.setQuantity(resultSet.getInt("quantity"));
                cartItem.setAdded_at(resultSet.getString("added_at"));
                cartItems.add(cartItem);
            }

        } catch (SQLException e) {


        }
        return cartItems;
    }

    public void updateCartItem(int userId, int goodsId, int quantity) throws SQLException {
        String query = "UPDATE shopping_cart SET quantity = ? WHERE user_id = ? AND goods_id = ?";
JDBCUtil jdbcUtil=new JDBCUtil();
        try (PreparedStatement statement = jdbcUtil.prepareStatement(query)) {
            statement.setInt(1, quantity);
            statement.setInt(2, userId);
            statement.setInt(3, goodsId);
            statement.executeUpdate();
        }
    }

    public void removeCartItem(int userId, int goodsId) throws SQLException {
        String query = "DELETE FROM shopping_cart WHERE user_id = ? AND goods_id = ?";
        JDBCUtil jdbcUtil=new JDBCUtil();
        try (PreparedStatement statement =jdbcUtil.prepareStatement(query)) {
            statement.setInt(1, userId);
            statement.setInt(2, goodsId);
            statement.executeUpdate();
        }
    }


    // 添加商品到购物车
    public boolean addToCart(Shopping_cart cart) throws SQLException {
        JDBCUtil jdbcUtil=new JDBCUtil();
        String query = "INSERT INTO shopping_cart (user_id, goods_id, quantity, added_at) VALUES (?, ?, ?, ?)";

            boolean resultSet = jdbcUtil.paramsUpdate(query,cart.getUser_id(), cart.getGoods_id(), cart.getQuantity(), cart.getAdded_at()
            );
          return resultSet;
        }

}
